package com.mine.frame.mylandemo.ui

import android.annotation.SuppressLint
import android.app.Service
import android.content.ComponentName
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.text.Editable
import android.util.Log
import com.blankj.utilcode.util.*
import com.mine.frame.common.base.BaseActivity
import com.mine.frame.mylandemo.R
import com.mine.frame.mylandemo.mvp.iview.IConnect
import com.mine.frame.mylandemo.mvp.presenter.ConnectPresenter
import com.mine.frame.mylandemo.service.MineConnectService
import com.mine.frame.mylandemo.service.MineConnectService.MineConnectServiceBinder
import com.mine.frame.mylandemo.service.SocketState
import com.swallowsonny.convertextlibrary.toHexString
import com.third.device.mg.serialport.service.MGSocketService
import kotlinx.android.synthetic.main.atv_connect.*

/**
 * company 广东玛格家居有限公司
 * @author smoker
 * @Date 2021/12/17
 * Description:
 */
@SuppressLint("SetTextI18n")
class ConnectAtv : BaseActivity<IConnect, ConnectPresenter>(), IConnect {
    companion object{
        //获取空调的温度--加
        const val READ_TEMP_AIR_ADD = "getAirTemp_add"
        //获取空调的温度--减
        const val READ_TEMP_AIR_SUBTRACT = "getAirTemp_subtract"

    }


    /*当前连接的IP地址 和 端口号*/
    private var ipStr = ""
    private var port = 61233
    private var mService: MineConnectService? = null
    private var nowTemp = -1 //当前温度
    private var readMode =  "" //当前读取的模式
    private val serviceConnect: ServiceConnection by lazy {
        object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                SnackbarUtils.with(tvInfo).setMessage("正在连接服务器...").showSuccess()
                service?.let {
                    if (it is MineConnectServiceBinder) {
                        mService = it.getService()
                        tvInfo.text = "获取到Android.Service控制对象"
                        initSocket()
                    }
                }
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                mService = null
            }
        }
    }

    override fun initLayoutId(): Int = R.layout.atv_connect

    override fun initPresenter(): ConnectPresenter = ConnectPresenter(this)

    override fun initLayoutAfter(savedInstanceState: Bundle?) {
        ipStr = intent?.getStringExtra("sel-ip").toString()
        edtIP.text = Editable.Factory.getInstance().newEditable(ipStr)
        addClickTouch()
    }

    private fun addClickTouch(){
        ClickUtils.applySingleDebouncing(arrayOf(btnConnect ,btnDisconnect ,btnSent ,btnOpenAir ,
            btnCloseAir ,btnColdAir ,btnHotAir ,btnWetAir ,btnWindAir
        ,btnWindAutoAir ,btnWindLowAir ,btnWindCentralAir ,btnWindHighAir
        ,btnTempAddAir ,btnTemp26Air ,btnTempSubtractAir
        ,btnValveDef ,btn1ValveLine2Off ,btn1ValveLine2On
        ,btn1ValveLine3Off ,btn1ValveLine3On
        ,btn2ValveLine2ColdOff ,btn2ValveLine2ColdOn ,btn2ValveLine2HotOff ,btn2ValveLine2HotOn)){
            when(it.id){
                R.id.btnConnect ->{
                    KeyboardUtils.hideSoftInput(this)
                    if (edtIP.text.isNullOrEmpty()){
                        SnackbarUtils.with(edtIP).setMessage("请输入IP地址").showWarning()
                        return@applySingleDebouncing
                    }else{
                        ipStr = edtIP.text.toString()
                    }


                    if (edtPort.text.isNullOrEmpty()){
                        SnackbarUtils.with(edtIP).setMessage("请输入端口号").showWarning()
                        return@applySingleDebouncing
                    }else{
                        port =edtPort.text.toString().toInt()
                        if (port < 1 || port > 65535){
                            SnackbarUtils.with(edtIP).setMessage("端口号异常(1,65535)").showWarning()
                            return@applySingleDebouncing
                        }
                    }
                    if (ipStr.isEmpty()){
                        SnackbarUtils.with(edtIP).setMessage("IP地址异常").showError()
                        return@applySingleDebouncing
                    }

                    onBindMineService()
                }
                R.id.btnDisconnect ->{
                    mService?.disconnect()
                }
                R.id.btnSent ->{
                    sentMsgToServer()
                }

                R.id.btnOpenAir ->{//空调开机
                    val command = mPresenter.commandAirOnOff(true)
                    mService?.sent(command)
                }

                R.id.btnCloseAir ->{//空调关机
                    val command = mPresenter.commandAirOnOff(false)
                    mService?.sent(command)
                }
                R.id.btnColdAir ->{//空调指令
                    val command = mPresenter.commandAirWorkMode(0)
                    mService?.sent(command)
                }
                R.id.btnHotAir ->{//空调制热
                    val command = mPresenter.commandAirWorkMode(1)
                    mService?.sent(command)

                }
                R.id.btnWetAir ->{//空调除湿
                    val command = mPresenter.commandAirWorkMode(2)
                    mService?.sent(command)

                }
                R.id.btnWindAir ->{//空调送风
                    val command = mPresenter.commandAirWorkMode(3)
                    mService?.sent(command)
                }
                R.id.btnWindAutoAir ->{//空调风速-自动
                    val command = mPresenter.commandAirWindMode(0)
                    mService?.sent(command)
                }
                R.id.btnWindLowAir ->{//空调风速-低
                    val command = mPresenter.commandAirWindMode(1)
                    mService?.sent(command)
                }
                R.id.btnWindCentralAir ->{//空调风速-中
                    val command = mPresenter.commandAirWindMode(2)
                    mService?.sent(command)
                }
                R.id.btnWindHighAir ->{//空调风速-高
                    val command = mPresenter.commandAirWindMode(3)
                    mService?.sent(command)
                }
                R.id.btnTempAddAir ->{//空调温度-加
                    mPresenter.addTemp()
                }
                R.id.btnTemp26Air ->{//空调温度-26℃
                    val command = mPresenter.setTemp(26)
                    mService?.sent(command)
                }
                R.id.btnTempSubtractAir ->{//空调温度-减
                    mPresenter.subtractTemp()
                }
                R.id.btnValveDef ->{//阀控制:默认(无效)
                    mPresenter.valveAirControl(0 ,0)
                }
                R.id.btn1ValveLine2Off ->{//阀控制:一路双线阀关
                    mPresenter.valveAirControl(1 ,0)
                }
                R.id.btn1ValveLine2On ->{//阀控制:一路双线阀开
                    mPresenter.valveAirControl(1 ,1)
                }
                R.id.btn1ValveLine3Off ->{//阀控制:一路三线阀关
                    mPresenter.valveAirControl(2 ,0)
                }
                R.id.btn1ValveLine3On ->{//阀控制:一路三线阀开
                    mPresenter.valveAirControl(2 ,1)
                }
                R.id.btn2ValveLine2ColdOff ->{//阀控制:两路双线阀-冷阀关
                    mPresenter.valveAirControl(3 ,0)
                }
                R.id.btn2ValveLine2ColdOn ->{//阀控制:两路双线阀-冷阀开
                    mPresenter.valveAirControl(3 ,1)
                }
                R.id.btn2ValveLine2HotOff ->{//阀控制:两路双线阀-热阀关
                    mPresenter.valveAirControl(3 ,2)
                }
                R.id.btn2ValveLine2HotOn ->{//阀控制:两路双线阀-热阀开
                    mPresenter.valveAirControl(3 ,3)
                }

            }
        }
    }

    /**
     * 绑定service
     */
    private fun onBindMineService() {
        mService?.let {
            tvInfo.text = "已Bind Android.Service"
            initSocket()
        }?:let {
            ServiceUtils.bindService(MineConnectService::class.java, serviceConnect, Service.BIND_AUTO_CREATE)
        }
    }

    /**
     * 创建Socket连接
     */
    private fun initSocket(){
        mService?.connect(ipStr ,port)
        mService?.addConnectStateListener {
            when(it){
                SocketState.SocketDisConnect ->{
                    tvInfo.text = "Socket暂未连接"
                    updateIndicator(false)
                }
                SocketState.SocketConnecting ->{
                    tvInfo.text = "Socket正在连接中..."
                }
                SocketState.SocketConnectSuccess ->{
                    tvInfo.text = "Socket已连接"
                    updateIndicator(true)
                }
                SocketState.SocketAddressInvalid ->{
                    tvInfo.text = "地址无效，请检查端口是否正确"
                }
                SocketState.SocketOutputStreamOpen ->{
                    tvInfo.text = "Socket 开启OutputStream通道"
                }// Socket 开启OutputStream通道
                SocketState.SocketOutputStreamClose ->{
                    tvInfo.text = "Socket 关闭OutputStream通道"
                }// Socket 关闭OutputStream通道
                SocketState.SocketInputStreamOpen ->{
                    tvInfo.text = "Socket 开启InputStream通道"
                }// Socket 开启InputStream通道
                SocketState.SocketInputStreamClose ->{
                    tvInfo.text = "Socket 关闭InputStream通道"
                }// Socket 关闭InputStream通道
                SocketState.SocketWriting ->{
                    tvInfo.text = "Socket 发送中"
                }//Socket 发送中
                SocketState.SocketWriteError ->{
                    tvInfo.text = "Socket 发送失败"
                }// Socket 发送失败
                SocketState.SocketWriteSuccess ->{
                    tvInfo.text = "Socket 发送成功"
                    showSuccess("发送成功")
                }// Socket 发送成功
                SocketState.SocketReading ->{
                    tvInfo.text = "Socket 读取中"
                }// Socket 读取中
                SocketState.SocketReadError ->{
                    tvInfo.text = "Socket 读取失败"
                }// Socket 读取失败
                SocketState.SocketReadSuccess->{
                    tvInfo.text = "Socket 读取成功"
                }// Socket 读取成功

            }
            Log.e("ConnectAtv -->" ,tvInfo.text.toString())
        }
        mService?.addReadInfoListener {
            LogUtils.d("服务器返回的数据:${it.toHexString(true)}")
            tvServiceMsg.text = it.toHexString(true)
            mPresenter.parseCommand(it)
        }
    }

    /**
     * 发送消息到服务器
     */
    private fun sentMsgToServer(){
        if (edtClientMsg.text.isNullOrEmpty()){
            SnackbarUtils.with(btnSent).setMessage("请输入发送内容").showWarning()
            return
        }
        val msg = edtClientMsg.text.toString()
        mService?.sent(msg)
    }


    private fun updateIndicator(connect:Boolean){
        val resId = if (connect){
            R.drawable.blue_circle
        }else{
            R.drawable.red_circle
        }
        viewIndicator.setBackgroundResource(resId)
    }


    override fun onDestroy() {
        super.onDestroy()
        mService?.let {
            ServiceUtils.unbindService(serviceConnect)
        }
    }

    override fun getMineConnectService(): MineConnectService? = mService

    override fun updateReadMode(mode: String) {
        this.readMode = mode
    }

    override fun getReadMode(): String = this.readMode

    override fun updateNowTemp(temp: Int) {
        this.nowTemp = temp
    }

    override fun getNowTemp(): Int = this.nowTemp
}